/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package extension.game.room.handler;

import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;
import extension.game.room.Game;
import extension.game.room.Player;
import extension.game.room.GameResponse;
import extension.game.room.RoomExtension;
import log.Debug;

/**
 *
 * @author daz
 */
public class ReadyHandler extends BaseClientRequestHandler {

    @Override
    public void handleClientRequest(User user, ISFSObject params) {
        Debug.d("handle ready request:" + user.getName());
//        String readyName = params.getUtfString(TienlenFlag.PLAYER_NAME);
        RoomExtension tienlenExtension = (RoomExtension) getParentExtension();
        Game game = tienlenExtension.getGame();
        Player[] listPlayers = game.getListPlayers();
        GameResponse response = tienlenExtension.getResponse();
        game.updateNumberInRoom();
        for (int i = 0; i < game.getMaxPlayer(); i++) {
            if (listPlayers[i] != null && listPlayers[i].getName().equals(user.getName())) {
                if (!listPlayers[i].isHost || game.canHostReady()) {
                    int curState = game.changePlayerState(i);
                    response.sendReadyState(i, curState, 1);
                    if (curState != -1) {
                        game.startGame();
                    }
                    if (!listPlayers[i].isHost) {
                        int numberReady = 0;
                        for (int j = 0; j < game.getMaxPlayer(); j++) {
                            if (listPlayers[j] != null && listPlayers[j].getState() == Player.READY) {
                                numberReady++;
                            }
                        }
                        if (numberReady == game.getNumberInRooms() - 1) {
                            game.doReady();
                        } else {
                            game.setIsHostTimeOut(false);
                        }
                    }
                } else {
                    response.sendReadyState(i, Player.NOT_READY, 0, user);
                }
                break;
            }
        }
    }
}
